var glob = require('glob');
var path = require('path');
var _root = path.resolve(__dirname, '..');
var appRoot = path.join(__dirname, 'src/');
var appRootPrefix = appRoot.replace(/\\/g, "\/");

class utils{
   static root(args){
     args = Array.prototype.slice.call(arguments, 0);
     var newPath = path.join.apply(path, [_root].concat(args));
    //  console.log(newPath);
     return newPath;
  }

  static getEntries(globPath, entries) {
    ////console.log('glob path: ' + globPath);
    var dirs = glob.sync(globPath);
    if (!dirs || dirs.length == 0) return;

    for (var i = 0; i < dirs.length; i++) {
        if (dirs[i].indexOf('/backup') > -1) continue; //keep...
        if (path.basename(dirs[i]).indexOf('.') > -1) continue; 

        var entryArr = [];
        var entry_key;// = path.basename(dirs[i].replace(appRootPrefix, ''));
        //console.log('entry_key: ' + entry_key);

        var files = glob.sync(dirs[i] + '/**/*.ts');
        //console.log('get files: ' + dirs[i] + '/**/*.ts');

        if (files && files.length > 0) {
            var entry, dirname, basename, dirBaseName, fileBasename;

            for (var j = 0; j < files.length; j++) {
                entry = files[j];
                dirname = path.dirname(entry);
                dirBaseName = path.basename(dirname);
                fileBasename = path.basename(entry, '.ts');
                
                //console.log(fileBasename);

                if (dirBaseName.toLowerCase().replace(/-/,'.') != fileBasename.toLowerCase()) continue;
                 entry_key = dirBaseName;
                 //console.log('find:' + fileBasename);
                if (entryArr) entryArr.push(entry);
            }

            if (entryArr && entryArr.length > 0 && entry_key) {
                 //console.log(entryArr);
                //console.log('add entry_key: ' + entry_key + ', entry: ' + entryArr);
                entries[entry_key] = entryArr;
            }
        }
    }
  }
}

module.exports = utils;
